package han.cirno.corrupt.components.update

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import java.io.File

/**
 * 我补药实现这么多版本的权限申请啊~~
 * @author CCirno
 */
object ApkUpdateHelper {
    fun installApk(context: Context,file: File){
        when{
            Build.VERSION.SDK_INT>=Build.VERSION_CODES.S-> installAfter12(context,file)
            Build.VERSION.SDK_INT>=Build.VERSION_CODES.O-> installAfter8Before12(context,file)
            else-> install(context, file)
        }
    }

    @RequiresApi(Build.VERSION_CODES.S)
    private fun installAfter12(context: Context,file: File){
        if(checkPermissionAfter8(context)){
            install(context, file)
            return
        }
        val intent=Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).also {
            it.setData(Uri.parse("package:${context.packageName}"))
        }
        context.startActivity(intent)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun installAfter8Before12(context: Context,file: File){
        if (checkPermissionAfter8(context)) {
            install(context, file)
            return
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun checkPermissionAfter8(context: Context):Boolean{
        return context.packageManager.canRequestPackageInstalls()
    }

    private fun install(context: Context,file: File){
        val intent=Intent(Intent.ACTION_VIEW).also {
            it.putExtra("name","")
            it.addCategory("android.intent.category.DEFAULT")
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            val type = "application/vnd.android.package-archive"
            if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N) {
                it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                it.setDataAndType(
                    FileProvider.getUriForFile(
                        context, context.packageName+".FILE_PROVIDER",file),
                    type
                )
            }else{
                it.setDataAndType(Uri.fromFile(file),type)
            }
        }
        context.startActivity(intent)
    }
}
